package com.baizhi.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baizhi.common.InsertGroup;
import com.baizhi.common.R;
import com.baizhi.domain.Result;
import com.baizhi.domain.StatusCode;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.service.CmfzAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ljh
 * @since 2020-08-18
 */
@Validated
@Controller
@RequestMapping("/cmfzAdmin")
public class CmfzAdminController {

    @Autowired
    private CmfzAdminService cmfzAdminService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    //@PreAuthorize("hasAuthority('banner:add')")
    @PreAuthorize("@ps.hasAnyPermission('banner:add')")
    @ResponseBody
    @RequestMapping("/test1")
    public R test1(){
        System.out.println("------------");
        return R.ok();
    }

    //@PreAuthorize("hasAuthority('banner:delete')")
    @PreAuthorize("@ps.hasAnyPermission('banner:delete')")
    @ResponseBody
    @RequestMapping("/test2")
    public R test2(){
        System.out.println("------------");
        return R.ok();
    }

    //@PreAuthorize("hasAnyRole('SUPERADMIN')")
    @PreAuthorize("@ps.hasAnyRole('SUPERADMIN')")
    @ResponseBody
    @RequestMapping("/test3")
    public R test3(){
        System.out.println("------------");
        return R.ok();
    }
    /**
     * 如果这里采用了分组校验，则实体类上面没有分组的校验规则将不生效
     * 解决：在实体类上给需要校验的加上分组的数组
     * @param cmfzAdmin
     * @return
     */
    //@PreAuthorize("hasAnyRole('ADMIN')")
    @PreAuthorize("@ps.hasAnyRole('ADMIN')")
    @ResponseBody
    @RequestMapping("/testAddAdmin")
    public R testAddAdmin(@Validated(InsertGroup.class) CmfzAdmin cmfzAdmin){
        //int i=1/0;
        System.out.println("------------");
        System.out.println(cmfzAdmin);
        return R.ok();
    }

    /**
     * 测试校验实体参数
     * @return
     */
    @ResponseBody
    @RequestMapping("/addAdmin1")
    public R addAdmin(@NotNull String username,@NotEmpty String password){
        System.out.println("------------");
        System.out.println("username=="+username);
        System.out.println("password=="+password);
        CmfzAdmin admin = new CmfzAdmin();
        admin.setUsername(username);
        admin.setPassword(bCryptPasswordEncoder.encode(password));
        cmfzAdminService.save(admin);
        return R.ok();
    }

    /**
     * 测试校验参数
     * @return
     */
    @ResponseBody
    @RequestMapping("/addAdmin2")
    public R addAdmin2(@Validated CmfzAdmin cmfzAdmin, BindingResult bindingResult){
        System.out.println("------------");
        System.out.println(cmfzAdmin);
        if (bindingResult.hasErrors()){
            Map map=new HashMap();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                //获取当前校验的属性
                String field = fieldError.getField();
                //获取校验错误信息
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            }
            return R.error().put("data",map);
        }
        return R.ok();
    }



    @ResponseBody
    @RequestMapping("/addAdmin")
    public R addAdmin(@NotEmpty String username,
                      @NotEmpty String password,
                      @RequestParam(name = "roleIds[]") List<Integer> roleIds){
        cmfzAdminService.addAdmin(username,password,roleIds);
        return R.ok();
    }


    @ResponseBody
    @RequestMapping("/selectAllAdmin")
    public R selectAllAdmin(Integer page,Integer limit){
        PageInfo<CmfzAdmin> pageInfo=cmfzAdminService.selectAllAdmin(page,limit);
        Map<String, Object> map = new HashMap<>();
        map.put("data",pageInfo.getList());
        map.put("count",pageInfo.getTotal());
        map.put("msg","查询成功");
        return R.ok(map);
    }

    @ResponseBody
    @RequestMapping("/deleteAdmin")
    public R deleteAdmin(Integer id){
        cmfzAdminService.deleteAdmin(id);
        return R.ok();
    }

    @ResponseBody
    @RequestMapping("/selectAdminAndRoleById")
    public R selectAdminAndRoleById(Integer id){
        //cmfzAdminService.selectAdminAndRoleById(id);
        return R.ok();
    }


    /**
     * 后台管理员的登录
     * @param
     * @param session
     * @return
     */
    //@RequestBody LoginDto loginDto
    @ResponseBody
    @RequestMapping("/login")
    public Result loginAdmin(String username,
                             String password,
                             String code,
                             HttpSession session){

        String realCode = (String) session.getAttribute("realCode");
        try{
            QueryWrapper<CmfzAdmin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",username);
            CmfzAdmin admin = cmfzAdminService.getOne(queryWrapper);
            if (StringUtils.isEmpty(code)|| !code.equals(realCode)){
                return new Result(false, StatusCode.ERROR,"验证码错误");
            }
            if (admin==null){
                return new Result(false, StatusCode.ERROR,"没有此账号");
            }
            if (!admin.getPassword().equals(password)){
                return new Result(false, StatusCode.ERROR,"密码错误");
            }
            //登录成功，移除session中的验证码
            session.removeAttribute("realCode");
            session.setAttribute("admin",admin);
            return new Result(true,StatusCode.OK,"登录成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"登录失败");
        }
    }

    @RequestMapping("/successForward")
    @ResponseBody
    public R successForward(){
        //return "redirect:/main.jsp";
        return R.ok("登录成功");
    }

    @ResponseBody
    @RequestMapping("/failureForward")
    public R failureForward(){
        //return "redirect:/login.jsp";
        return R.error("账号或密码错误");
    }

    /**
     * 验证码的获取
     * @param session
     * @param resp
     * @throws IOException
     */
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse resp) throws IOException {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String realCode = lineCaptcha.getCode();
        session.setAttribute("realCode",realCode);
        OutputStream out = resp.getOutputStream();
        lineCaptcha.write(out);
        out.close();
    }

}
